package com.workflow.service.impl;

import java.util.Date;
import java.util.List;

import com.common.util.AbstractManager;
import com.common.util.DateHelper;
import com.common.util.PagerModel;
import com.workflow.bean.Inputdept;
import com.workflow.service.InputdeptService;

public class InputdeptServiceImpl extends AbstractManager implements
		InputdeptService {

	public void addInputdept(Inputdept inputdept) {
		StringBuilder inputno = new StringBuilder();//32位以内
		Long count = 0L;
		String hql = "select count(*) from Inputdept";//数量统计6位
		count = (Long) this.getHibernateTemplate().find(hql).get(0);
		count %= 1000L;
		
		Long num = Long.parseLong(DateHelper.dateToStr(new Date(), "yyyyMMddHms"));//13位
		num *= 1000L;		
		num += count;
		
		String deptcode = inputdept.getDepartmentByDeptcode().getDeptcode();
		inputno.append(deptcode.substring(0, deptcode.length()>6?6:deptcode.length()));//最好有个简称且不超过6位
		inputno.append("-RK-");
		inputno.append(num);
		
		inputdept.setInputno(inputno.toString());
		inputdept.setStartdate(new Date());
		
		this.getHibernateTemplate().save(inputdept);
	}

	@SuppressWarnings("unchecked")
	public List<Inputdept> findAllInputdept() {
		String hql = "from Inputdept ipd order by ipd.departmentByDeptcode.deptcode, ipd.inputno";
		return this.getHibernateTemplate().find(hql);
	}

	public Inputdept findInputdept(String inputno) {
		return (Inputdept) this.getHibernateTemplate().load(Inputdept.class, inputno);
	}

	public PagerModel findInputdeptForPager() {
		String hql = "from Inputdept ipd order by ipd.departmentByDeptcode.deptcode, ipd.inputno";
		return searchPaginated(hql);
	}

	public void removeInputdept(String inputno) {
		String hql = "from Inputdeptdetail idd where idd.inputdept.inputno = ?";
		List list = this.getHibernateTemplate().find(hql,inputno);
		if(list == null || list.size() == 0) {
			Inputdept inputdept = (Inputdept) this.getHibernateTemplate().load(Inputdept.class, inputno);
			if(inputdept != null) {
				this.getHibernateTemplate().delete(inputdept);
			}
		}else {
			throw new RuntimeException("you should remove the items of inputdeptdetail with inputno :" + inputno);
		}
	}

	public void updateInputdept(Inputdept inputdept) {
		this.getHibernateTemplate().update(inputdept);
	}

}
